import { error, success } from '../utils/Response'
import fs from 'fs/promises'
import path from 'path'
import jwt from 'jsonwebtoken'
import { secret } from '../config/constant'
import redis from '../db/redis'
import md5 from '../utils/crypto'
import sendMail from '../utils/nodemailer'
import { ctx, next } from '../middlewares/errorHandle'
import { getUserinfo, updateUserinfo, createUser, createBlog, getOneBlog, createComment, getBlogList, getComments, getUserinfoById } from '../services'
export async function upload(ctx: ctx, next: next) {
  const file: any = ctx.request.files?.file
  if (file) {
    success(ctx, '上传成功', { url: '/static/' + file.newFilename })
  } else {
    error(ctx, 400, '文件不能为空')
  }
}
export async function deleteFile(ctx: ctx, next: next) {
  const { url } = ctx.request.query
  console.log('url:' + url)

  try {
    await fs.unlink(`${path.join(__dirname, `../../public${url}`)}`)
    success(ctx, '文件删除成功')
  } catch (err) {
    error(ctx, 500, '文件删除失败')
  }
}

export interface newUserinfoType {
  nickName?: string
  email?: string
  gender?: number
  avatar?: string
}
export async function GetUserinfo(ctx: ctx, next: next) {
  const userinfo = await getUserinfo({ user_id: ctx.user.id })
  if (userinfo) {
    success(ctx, '获取个人信息成功', userinfo)
  } else {
    error(ctx, 202, '用户不存在')
  }
}
export async function GetUserinfoById(ctx: ctx, next: next) {
  const { userid } = ctx.params
  const userinfo = await getUserinfoById(userid)
  if (userinfo) {
    success(ctx, '获取个人信息成功', userinfo)
  } else {
    error(ctx, 202, '用户不存在')
  }
}

export async function UpdateUserinfo(ctx: ctx, next: next) {
  const { email, emailKey } = ctx.request.body
  if (email) {
    const userinfo = await getUserinfo({ email })
    if (userinfo) {
      error(ctx, 201, '邮箱已存在')
    } else if (emailKey === (await redis.get(`${email}Key`))) {
      const { emailKey, ...obj } = ctx.request.body
      await updateUserinfo(ctx.user.id, obj)
    } else {
      error(ctx, 400, '无效验证码或已过期')
    }
  } else {
    const { emailKey, ...obj } = ctx.request.body
    await updateUserinfo(ctx.user.id, obj)
  }
  success(ctx, '修改成功')
}

export async function isExist(ctx: ctx, next: next) {
  const { userName } = ctx.request.query

  const userinfo = await getUserinfo({ userName })
  if (userinfo) {
    error(ctx, 201, '用户名已存在')
  } else {
    success(ctx, '该用户名可用')
  }
}
export async function isExistEmail(ctx: ctx, next: next) {
  const { email } = ctx.request.query

  const userinfo = await getUserinfo({ email })
  if (userinfo) {
    error(ctx, 201, '邮箱已存在')
  } else {
    success(ctx, '该邮箱可用')
  }
}
export async function register(ctx: ctx, next: next) {
  const { userName, email, emailKey } = ctx.request.body
  const userinfo1 = await getUserinfo({ userName })
  const userinfo2 = await getUserinfo({ email })
  if (userinfo1) {
    error(ctx, 201, '用户名已存在')
  } else if (userinfo2) {
    error(ctx, 201, '邮箱已存在')
  } else {
    if (emailKey === (await redis.get(`${email}Key`))) {
      delete ctx.request.body.emailKey
      await createUser(ctx.request.body)
      success(ctx, '注册成功')
    } else {
      error(ctx, 400, '验证码不正确或已过期')
    }
  }
}
export async function login(ctx: ctx, next: next) {
  const { userNameOrEmail, password } = ctx.request.body
  const userinfo1 = await getUserinfo({ userName: userNameOrEmail, password: md5(password) })
  const userinfo2 = await getUserinfo({ email: userNameOrEmail, password: md5(password) })

  console.log(userinfo2)
  console.log(userinfo2?.id)

  if (userinfo1) {
    const token = jwt.sign({ id: userinfo1.user_id }, secret, { expiresIn: '7day' })
    success(ctx, '登陆成功', token)
  } else if (userinfo2) {
    const token = jwt.sign({ id: userinfo2.user_id }, secret, { expiresIn: '7day' })
    success(ctx, '登陆成功', token)
  } else {
    error(ctx, 400, '账号或密码错误')
  }
}
export async function sendEmail(ctx: ctx, next: next) {
  const { email } = ctx.request.body
  //这里如果发送的邮箱不存在也会报错550 mail content denied
  const code = await sendMail(email)
  success(ctx, '验证码发送成功')
  await redis.set(`${email}Key`, code, 30)
}

export async function CreateBlog(ctx: ctx, next: next) {
  const blog = {
    ...ctx.request.body,
    user_id: ctx.user.id
  }
  const currentBlog = await createBlog(blog)
  success(ctx, '发布成功', currentBlog)
}
export async function GetOneBlog(ctx: ctx, next: next) {
  const { blogid } = ctx.params
  const result = await getOneBlog(blogid)

  if (result) {
    success(ctx, '查询成功', result)
  } else {
    error(ctx, 201, '此博客不存在')
  }
}
export async function GetBlogList(ctx: ctx, next: next) {
  const { page, limit } = ctx.request.query

  const result = await getBlogList({ page: Number(page), limit: Number(limit) })
  //count - 一个整数 - 与查询匹配的记录总数(并不是获得的总数)
  //rows - 一个数组对象 - 获得的记录
  success(ctx, '查询博客列表成功', result)
}

export async function GetAllBlogByUser(ctx: ctx, next: next) {
  const { userid } = ctx.params
  const { page, limit } = ctx.request.query
  const result = await getBlogList({ user_id: userid, page: Number(page), limit: Number(limit) })
  success(ctx, '查询用户所有博客成功', result)
}
export async function CreateComment(ctx: ctx, next: next) {
  const comment = {
    ...ctx.request.body,
    blog_id: ctx.params.blogid,
    user_id: ctx.user.id
  }
  const currentComment = await createComment(comment)
  success(ctx, '发布成功', currentComment)
}
export async function GetComments(ctx: ctx, next: next) {
  const { blogid } = ctx.params
  const { page, limit } = ctx.request.query

  const result = await getComments(blogid, Number(page), Number(limit))
  success(ctx, '查询评论成功', result)
}
